package com.leetroll.app.config;

import com.alibaba.fastjson.JSONObject;
import com.leetroll.app.utils.AppJwtTokenUtil;
import com.leetroll.common.utils.UserUtil;
import com.leetroll.common.constant.CharConstant;
import com.leetroll.common.enums.ECode;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 拦截器 校验token是否过期
 */
@Component
@Slf4j
public class AuthenticationTokenFilter extends OncePerRequestFilter {

    private final AppJwtTokenUtil jwtTokenUtil;

    private static final List<String> AuthNeedUri = new ArrayList<>();

    static {
        AuthNeedUri.add("/app/order/");
        AuthNeedUri.add("/app/cart/");
        AuthNeedUri.add("/app/user/");
        AuthNeedUri.add("/app/action/");
        AuthNeedUri.add("/app/item/download-attach/");
    }

    @Autowired
    public AuthenticationTokenFilter(AppJwtTokenUtil jwtTokenUtil) {
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain chain)
            throws ServletException, IOException {
        String accessToken = request.getHeader("Authorization");
        UserUtil.setUserId(jwtTokenUtil.getUserId(request));

        String requestURI = request.getRequestURI();
        if (!varifyNeedAuth(requestURI)) {
            chain.doFilter(request, response);
            return;
        }
        setResponse(response);
        Map<String, Object> result = new HashMap<>(CharConstant.NUM_THREE);
        if (accessToken == null) {
            result.put("code", ECode.UNAUTHORIZED);
            result.put("msg", "fail");
            response.getWriter().write(JSONObject.toJSONString(result));
            return;
        }
        //判断accessToken是否已过期  过期返回token失效, 需刷新token
        if (jwtTokenUtil.isExpiration(accessToken)) {
            response.setStatus(ECode.UNAUTHORIZED);
            response.getWriter().write(JSONObject.toJSONString(result));
            return;
        }
        chain.doFilter(request, response);
    }

    private boolean varifyNeedAuth(String requestURI) {
        for (String uri : AuthNeedUri) {
            if (requestURI.contains(uri)) {
                return true;
            }
        }
        return false;
    }

    private static void setResponse(@NotNull HttpServletResponse response) {
        response.setStatus(ECode.SUCCESS);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
    }


}
		

